// pages/components/goodLive/goodLive.js
const app = getApp();
let livePlayer;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    'goodId': {
      type:String,
      observer: 'requestLiveRoom'
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    roomId:''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    requestLiveRoom: function (goodId) {
      var that = this;
      console.log(goodId);
      wx.request({
        url: app.globalData.liverqurl,
        data: {
          map: 'applet_appletlive_goods_has_live',
          gid: goodId
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            livePlayer = requirePlugin('live-player-plugin');
            var allData = res.data.data;
            console.log('商品相关直播',allData)
            that.setData({
              allData:allData
            })
            
            if(allData.length>0){
              for (let i = 0; i < allData.length; i++) {
                if (allData[i].status == 101) {
                  that.setData({
                    roomId: allData[i].room_id,
                  })
                  return;
                }
              };
              that.getLiveStatus(0,allData[0].room_id)
            }
            

          } else {

          }
        },
        complete: function () {

        }
      });
    },
    getLiveStatus(i,roomId){
      let allData=this.data.allData,that=this;
      let allDataLength=allData.length-1;
      livePlayer.getLiveStatus({ room_id: roomId }).then(res => {
        console.log('相关直播',res)
        //当直播状态有更新时，传递给后台
        if(allData[i].status!=res.liveStatus){
          console.log('更新直播状态',allData[i].status,res.liveStatus)
          app.updateLiveStatus(allData[i].room_id,res.liveStatus)
        }
        if (res.liveStatus== 101) {
          that.setData({
            roomId: roomId
          })
        }else{
          i=i+1;
          if(i<=allDataLength){
            this.getLiveStatus(i,allData[i].room_id)
          }
        }
        
      }).catch(err => {
        console.log(err)
      })
    }
  }
})
